package servlet;

import dao.DaoAlbum;
import dao.DaoTagAlbum;
import entidades.Album;
import entidades.TagAlbum;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Global;
import util.Upload;
import util.Util;

/**
 *
 * @author João Pedro
 */
@WebServlet(name = "ServletCadAlbum", urlPatterns = {"/ServletCadAlbum"})
public class ServletCadAlbum extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        Upload upload = new Upload(getServletContext().getRealPath(Global.albumData_path));
        List list = upload.processRequest(request);
        Map<String, String> map = upload.getFormValues(list);
        System.out.println("--" + upload.getPath());
        String nome = map.get("nome");
        String tags = map.get("tags");
        String imagem = map.get("imagem");
        if (Util.valida(Util.CAMPO_TEXTO, nome) && Util.valida(Util.CAMPO_ARQUIVO, imagem) && Util.valida(Util.CAMPO_TEXTO, tags)) {
            Album album = new Album(nome, imagem);
            
            String[] str = tags.split(";");
            salvarTags(str, album);
            //Salva o album no banco de dados
            new DaoAlbum().insert(album);

            RequestDispatcher rd = request.getRequestDispatcher("homeAdmin.jsp");
            rd.forward(request, response);
        } else {
            request.setAttribute("erro", "Informações Inválidas");
            RequestDispatcher rd = request.getRequestDispatcher("cadAlbum.jsp");
            rd.forward(request, response);
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    private void salvarTags(String[] str, Album a) {

        //Verificar se a tagMusica existe, e existir adicionar a musica a ela, se não criar a tag
        for (String name : str) {
            String tagName = name.trim();
            List<TagAlbum> l = new DaoTagAlbum().buscaTagNome(tagName);
            if (l.isEmpty()) {
                //Cria tag e adiciona a música a ela
                TagAlbum tag = new TagAlbum(tagName);
                tag.addAlbum(a);
                a.addTagAlbum(tag);
            } else {
                //Adiciona a música a tag
                TagAlbum tag = l.get(l.indexOf(new TagAlbum(tagName)));
                tag.addAlbum(a);
                a.addTagAlbum(tag);
            }
        }
    }
}
